package distributed.controller;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import distributed.entity.Event;
import distributed.entity.EventModel;
import distributed.entity.Choice;
import distributed.entity.User;

import server.ClientState;
import xml.Message;

/**
 * Controller to handle users and moderators signing in to an event
 * @author Marcus Menghini
 *
 */
public class EventSignInController implements IProtocolController{

	/** Processes a message from a client */
	public Message process(ClientState state, Message request) {
		String xmlString;
		//Get our request node
		Node base = request.contents.getFirstChild();
		NamedNodeMap map = base.getAttributes(); // And its attributes		
		
		// We need the user data too
		String userName = base.getFirstChild().getAttributes()
							.getNamedItem("name").getNodeValue();	
		String id = map.getNamedItem("id").getNodeValue(); //Grab the event id
		// Get the event
		Event event = EventModel.getInstance().getEvent(id);
		//If event doesn't exist, we're done
		if (event == null) {
			xmlString = Message.responseHeader(request.id(), "This event does not exist") + 
				"<signInResponse id='" + id + "' type='closed' question='Does not Exist' " +
						"numChoices='0' numRounds='0' position='0'/></response>";
			return new Message(xmlString);
		}
		//Else, get the next index
		int position = event.next(state.id());
		
		xmlString =  "<signInResponse id='" + id + "' type='" +
		(event.isOpen() ? "open" : "closed") + "' question=\"" + event.getQuestion() +
		"\" numChoices='" + event.getCount() + "' numRounds='" + event.getRounds() +
		"' position='" + position + "'>";
		
		//If Position is -1, it means we're full
		if (position == -1) {
			xmlString = Message.responseHeader(request.id(), "This event is full") + 
							xmlString +"</signInResponse></response>";
			return new Message(xmlString);
		} //Else try signing in
		else if (!event.signIn(new User(userName, state.id(), position))) {
			xmlString = Message.responseHeader(request.id(), "This name is already taken") + 
							xmlString +"</signInResponse></response>";
			return new Message(xmlString);
		}
		
		xmlString = Message.responseHeader(request.id()) + xmlString;
		
		// If we've got through all that, compose all of the data about the event
		for (int i=0; i < event.getCount(); i++) {
			Choice l = event.getLines()[i];
			if (l.getChoice() != null && !l.getChoice().equals(""))
				xmlString += "<choice value=\"" + l.getChoice() + "\" index='" + i + "'/>";
		}
		xmlString += "</signInResponse></response>";
		//And send it off
		Message send = new Message(xmlString);
		
		return send;
	}

	/**
	 * @return EventSignInController
	 */
	public IProtocolController newCopy() {
		return new EventSignInController();
	}

}
